package com.myproject.service;

import com.myproject.mapper.UserMapper;

import com.myproject.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;
@Component
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    /**
     *     实现UserDetailsService中的loadUserByUsername方法
     *     loadUserByUsername会从表单中获取name为"username"和"password"的字段，
     *     实现此方法会传入username来让我们验证，即我们从数据库中查询这个用户是否存在，
     *     然后将查询到的密码传给BCryptPasswordEncoder对象，这个对象会自动帮我们去验证密码正确
     *      BCryptPasswordEncoder采用SHA-256 +随机盐+密钥对密码进行加密，这个方法不能传入明文密码
     */

    @Autowired
    UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users user = userMapper.queryUserByName(username);//从数据库获取User对象
        if (user==null){//如果用户并不存在则会抛出异常
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<GrantedAuthority> role = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        //设置用户角色
        //   我们可以从User的构造器中看到，User中需要传入三个值，即用户名，加密的密码和用户角色
        //   public User(String username, String password, Collection<? extends GrantedAuthority> authorities)

        return new User(user.getName()
                ,new BCryptPasswordEncoder().encode(user.getPwd()),role);
        //这个User是package org.springframework.security.core.userdetails下的User，并不是我们的实体类对象。

    }

}
